package com.example.wendao.view.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.ImgUtils;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.NewsPics;
import com.example.wendao.model.entity.User;
import com.example.wendao.view.adapter.ImagePickerAdapter;
import com.example.wendao.view.ui.activity.MainActivity;
import com.example.wendao.view.ui.activity.RequestImgTestActivity;
import com.example.wendao.view.utils.BitmapUtils;
import com.example.wendao.view.utils.GlideImageLoader;
import com.example.wendao.view.widget.SelectDialog;
import com.example.wendao.viewmodel.NewsViewModel;
import com.example.wendao.viewmodel.UserViewModel;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Publish_newsFragment extends Fragment implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    //返回发布页
    public Button news_back_to_publish;

    //新闻类型
    public RadioGroup select;
    private RadioButton imp_news;
    private RadioButton tec_news;
    private RadioButton life_news;
    private RadioButton amu_news;
    //提交新闻类型
    public int type;
    //新闻标题
    public EditText news_title;
    //判断新闻标题是否为空
    public boolean title_check;
    //添加照片
    public RecyclerView add_news;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; // 当前选择的所有图片
    private int maxImgCount = 3;               // 允许选择图片最大数

    //新闻内容
    public EditText news_content;
    //判断新闻标题是否为空
    public boolean context_check;
    //提交新闻
    public Button news_publish;
    //news对象
    public News news_obj;

    private NewsViewModel newsViewModel;

    private UserViewModel userViewModel;

    // 图片的字节数组类别
    private List<byte[]> imgList;

    public Publish_newsFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_publish_news, container, false);
        news_back_to_publish=view.findViewById(R.id.news_back_to_publish);
        select = view.findViewById(R.id.select);
        imp_news = view.findViewById(R.id.imp_news);
        tec_news = view.findViewById(R.id.tec_news);
        life_news = view.findViewById(R.id.life_news);
        amu_news = view.findViewById(R.id.amu_news);
        news_title = view.findViewById(R.id.news_title);
        news_content = view.findViewById(R.id.news_content);
        news_publish = view.findViewById(R.id.news_publish);
        news_obj = new News();
        newsViewModel = new ViewModelProvider(App.getInstance()).get(NewsViewModel.class);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        // 初始化上传图片组件
        initWidget(view);

        //返回按钮返回发布界面
        news_back_to_publish.setOnClickListener(view1 -> Navigation.findNavController(getView()).navigate(R.id.action_publish_newsFragment_to_fragment_publish));
        //提交按钮
        news_publish.setOnClickListener(view12 -> {
            //确认提交新闻提示框
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("提交提示");
            builder.setMessage("确认提交此篇新闻");
            AlertDialog alertDialog = builder.create();
            //点击确认进行信息的查验
            builder.setPositiveButton("确定", (dialog, which) -> {
                //获取选中项,判断是否选了类型
                type = 0;
                if (select.getCheckedRadioButtonId() == R.id.imp_news) {
                    type = 1; //选择了要闻
                } else if (select.getCheckedRadioButtonId() == R.id.tec_news) {
                    type = 2; //选择了科技
                } else if (select.getCheckedRadioButtonId() == R.id.life_news) {
                    type = 3; //选择了生活
                } else if (select.getCheckedRadioButtonId() == R.id.amu_news) {
                    type = 4; // 选择了娱乐
                } else {
                    // 显示提示框
                    Toast.makeText(getActivity(), getResources().getString(R.string.no_select), Toast.LENGTH_SHORT).show();
                }

                // 判断新闻标题是否为空
                title_check = false;
                if (news_title.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.no_title), Toast.LENGTH_SHORT).show();
                    title_check = false;
                } else title_check = true;


                //判断新闻内容是否为空
                context_check = false;
                if (news_content.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), getResources().getString(R.string.no_content), Toast.LENGTH_SHORT).show();
                    context_check = false;
                } else context_check = true;

                //数据库上传信息
                if (type != 0&& title_check && context_check)
                {
                    Date date = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String time = format.format(date);
                    news_obj.setNewsType(type);
                    news_obj.setNewsTitle(news_title.getText().toString());
                    news_obj.setNewsContent(news_content.getText().toString());
                    news_obj.setNewsAuthorId(userViewModel.getCurrentUser().getUserId());
                    news_obj.setNewsTime(time);
                    newsViewModel.addNews(news_obj);
                    // 上传图片操作
                    uploadImage(selImageList);
                    if (imgList != null && imgList.size() != 0) {
                        List<NewsPics> newsPicsList = new ArrayList<>();
                        for (byte[] bs : imgList){
                            NewsPics newsPics = new NewsPics();
                            newsPics.setNewsPic(bs);
                            newsPics.setNewsPicFatherId(newsViewModel.findLatestNews().getNewsId());
                            newsPicsList.add(newsPics);
                        }
                        NewsPics[] newsPicsArray = new NewsPics[newsPicsList.size()];
                        newsViewModel.addNewsPic(newsPicsList.toArray(newsPicsArray));
                        AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
                        builder2.setTitle("亲爱的闻道道友：");
                        builder2.setMessage("恭喜您已经发布成功啦，快去看看吧！");
                        builder2.setPositiveButton("确定", (dialogInterface, i) -> Navigation.findNavController(view).navigate(R.id.action_publish_newsFragment_to_fragment_new));
                        builder2.show();
                    } else {
                        AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
                        builder2.setTitle("亲爱的闻道道友：");
                        builder2.setMessage("请您上传一张图片把！");
                        builder2.setPositiveButton("确定", (dialog1, which1) -> {});
                        builder2.show();
                    }
                }
            });
            //点击取消
            builder.setNegativeButton("取消", (dialog, which) -> Toast.makeText(getActivity(), getResources().getString(R.string.cancle_publish), Toast.LENGTH_SHORT).show());
            builder.setNeutralButton("关闭窗口", (dialog, which) -> Toast.makeText(getActivity(), getResources().getString(R.string.cancle_publish), Toast.LENGTH_SHORT).show());
            builder.show();
        });
        return view;
    }

    private void initWidget(View view) {
        RecyclerView recyclerView = view.findViewById(R.id.add_news);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(view.getContext(), selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(view.getContext(), 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this.getActivity(), R.style.transparentFrameWindowStyle, listener, names);
        if (!this.getActivity().isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog((parent, view1, position1, id) -> {
                    switch (position1) {
                        case 0: // 直接调起相机
                            //打开选择,本次允许选择的数量
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent = new Intent(this.getActivity(), ImageGridActivity.class);
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS,true); // 是否是直接打开相机
                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                            break;
                        case 1:
                            //打开选择,本次允许选择的数量
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent1 = new Intent(this.getActivity(), ImageGridActivity.class);
                            startActivityForResult(intent1, REQUEST_CODE_SELECT);
                            break;
                        default:
                            break;
                    }
                }, names);
                break;
            default:
                Intent intentPreview = new Intent(this.getActivity(), ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS,true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            // 添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data
                        .getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null){
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data
                        .getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null){
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }


    /**
     * 上传图片
     * @param pathList 要上传的图片列表
     */
    private void uploadImage(ArrayList<ImageItem> pathList) {
        Map<Integer, String> files = new HashMap<>();
        for (int i = 0; i < pathList.size(); i++) {
            String newPath = BitmapUtils
                    .compressImageUpload(pathList.get(i).path); // 保存到临时文件夹
            files.put(i, newPath);
        }
        imgList = ImgUtils.getBaosBytePathMap(files);
    }

}
